<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class LadderPriceRule implements Rule
{
    public $message;

    /**
     * Create a new rule instance.
     *
     */
    public function __construct()
    {
        $this->message = '';
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string $attribute
     * @param mixed $ladder_price
     * @return bool
     */
    public function passes($attribute, $ladder_price)
    {
        $keys = array_keys($ladder_price);

        if (!empty(array_diff($keys, ['one', 'two', 'three', 'four']))) {
            $this->message = '阶梯价格策略数据格式错误';
            return false;
        }

        foreach ($keys as $key) {
            if (!is_numeric($ladder_price[$key]['min']) || !is_numeric($ladder_price[$key]['max']))  {
                $this->message = '设备定价时间必须为数字';
                return false;
            }  else if (!is_numeric($ladder_price[$key]['price'])) {
                $this->message = '设备定价金额必须为数字';
                return false;
            }
        }

        if ($ladder_price['one']['min'] != 0) {
            $this->message = '设备定价阶梯必须从0分钟开始计算';
            return false;
        } else if ($ladder_price['one']['min'] >= $ladder_price['one']['max']) {
            $this->message = '1级定价阶梯时间范围填写错误，开始时间必须小于结束时间';
            return false;
        } else if ($ladder_price['two']['min'] != $ladder_price['one']['max']) {
            $this->message = '2级定价阶梯必须从1级定价结束时间开始';
            return false;
        } else if ($ladder_price['two']['min'] >= $ladder_price['two']['max']) {
            $this->message = '2级定价阶梯时间范围填写错误，开始时间必须小于结束时间';
            return false;
        } else if ($ladder_price['three']['min'] != $ladder_price['two']['max']) {
            $this->message = '3级定价阶梯必须从2级定价结束时间开始';
            return false;
        } else if ($ladder_price['three']['min'] >= $ladder_price['three']['max']) {
            $this->message = '3级定价阶梯时间范围填写错误，开始时间必须小于结束时间';
            return false;
        } else if ($ladder_price['four']['min'] != $ladder_price['three']['max']) {
            $this->message = '4级定价阶梯必须从3级定价结束时间开始';
            return false;
        }

        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return $this->message;
    }
}
